package org.dromara.business.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.business.domain.BusinessConfig;
import org.dromara.business.domain.BusinessConfigType;
import org.dromara.business.domain.bo.BusinessConfigTypeBo;
import org.dromara.business.domain.vo.BusinessConfigTypeVo;
import org.dromara.business.mapper.BusinessConfigTypeMapper;
import org.dromara.business.service.BusinessConfigService;
import org.dromara.business.service.BusinessConfigTypeService;
import org.dromara.common.core.constant.TenantConstants;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 业务参数配置类型Service业务层处理
 *
 * @author zj
 * @date 2024-06-28
 */
@RequiredArgsConstructor
@Service
public class BusinessConfigTypeServiceImpl extends ServiceImpl<BusinessConfigTypeMapper, BusinessConfigType> implements BusinessConfigTypeService {

    private final BusinessConfigTypeMapper baseMapper;
    private final BusinessConfigService businessConfigService;

    /**
     * 查询业务参数配置类型
     */
    @Override
    public BusinessConfigTypeVo queryById(Long configTypeId) {
        return baseMapper.selectVoById(configTypeId);
    }

    /**
     * 查询业务参数配置类型列表
     */
    @Override
    public TableDataInfo<BusinessConfigTypeVo> queryPageList(BusinessConfigTypeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BusinessConfigType> lqw = buildQueryWrapper(bo);
        Page<BusinessConfigTypeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询业务参数配置类型列表
     */
    @Override
    public List<BusinessConfigTypeVo> queryList(BusinessConfigTypeBo bo) {
        LambdaQueryWrapper<BusinessConfigType> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BusinessConfigType> buildQueryWrapper(BusinessConfigTypeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BusinessConfigType> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getConfigName()), BusinessConfigType::getConfigName, bo.getConfigName());
        lqw.eq(StrUtil.isNotBlank(bo.getConfigType()), BusinessConfigType::getConfigType, bo.getConfigType());
        lqw.orderByDesc(BusinessConfigType::getCreateTime);
        return lqw;
    }

    /**
     * 新增业务参数配置类型
     */
    @Override
    public Boolean insertByBo(BusinessConfigTypeBo bo) {
        BusinessConfigType add = MapstructUtils.convert(bo, BusinessConfigType.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setConfigTypeId(add.getConfigTypeId());
        }
        return flag;
    }

    /**
     * 修改业务参数配置类型
     */
    @Override
    public Boolean updateByBo(BusinessConfigTypeBo bo) {
        BusinessConfigType update = MapstructUtils.convert(bo, BusinessConfigType.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BusinessConfigType entity) {

    }

    /**
     * 批量删除业务参数配置类型
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        List<BusinessConfigType> list = this.lambdaQuery().in(BusinessConfigType::getConfigTypeId, ids).list();
        List<String> keys = StreamUtils.toList(list, BusinessConfigType::getConfigType);
        businessConfigService.deleteWithValidByKeys(keys);
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 同步超级管理员的业务参数配置到当前租户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int syncConfig() {
        if (LoginHelper.isSuperAdmin()) {
            return 1;
        }
        this.remove(new LambdaQueryWrapper<>());
        businessConfigService.remove(new LambdaQueryWrapper<>());
        List<BusinessConfigType> typeList = TenantHelper.ignore(() -> this.lambdaQuery()
            .eq(BusinessConfigType::getTenantId, TenantConstants.DEFAULT_TENANT_ID).list());
        List<BusinessConfig> configList = TenantHelper.ignore(() -> businessConfigService.lambdaQuery()
            .eq(BusinessConfig::getTenantId, TenantConstants.DEFAULT_TENANT_ID).list());
        typeList.forEach(type -> {
            type.setTenantId(null);
            type.setConfigTypeId(null);
        });
        configList.forEach(config -> {
            config.setTenantId(null);
            config.setBusinessConfigId(null);
        });
        this.saveBatch(typeList);
        businessConfigService.saveBatch(configList);
        return 1;
    }
}
